<template>
	<view class="user-info-page">
		<!-- 头像区域 -->
		<view class="avatar-block">
			<image class="user-avatar" :src="formData.avatar || '/static/images/默认用户头像.png'" @click="reviseAvatar"
				mode="aspectFill" />
		</view>

		<!-- 表单区域（使用input框） -->
		<form class="info-form">
			<!-- 昵称 -->
			<view class="form-item">
				<label class="form-label">昵称</label>
				<input class="form-input" type="text" v-model="formData.nickname" placeholder="请输入昵称" />
			</view>

			<!-- 性别 -->
			<view class="form-item">
			  <label class="form-label">性别</label>
			  <picker @change="onChangeGender" :value="formData.gender" :range="genderArray" range-key="label">
			    <input class="form-input" type="text" v-model="formData.genderValue" placeholder="请选择性别" />
			
			  </picker>
			</view>

			<!-- 国家 -->
			<view class="form-item">
				<label class="form-label">国家</label>
				<input class="form-input" type="text" disabled="true"  placeholder="中国" />
			</view>

			<!-- 省份 -->
			<view class="form-item">
				<label class="form-label">省份</label>
				<picker @change="onChangeProvinc" @click="handProvinc"  :range="provinceArray" range-key="district">
					<input class="form-input" type="text" v-model="formData.province" placeholder="请选择省份" />
				</picker>
				
			</view>

			<!-- 城市 -->
			<view class="form-item">
				<label class="form-label">城市</label>
				
			<picker @change="onChangeCity"  :range="cityArray" range-key="district">
				<input class="form-input" type="text" v-model="formData.city" placeholder="请选择省份" />
			</picker>
			</view>

			<button class="btn" @click="editUser">提交</button>
		</form>
	</view>
</template>

<script setup>
import { ref } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { putUserInfo,getProvince,getCity } from '@/api/common.js';
import { base_url } from '@/request/request.js'

// 省份的数据
const provinceArray = ref([])

// 城市的数据
const cityArray = ref([])

// 性别
const genderArray = ref([
  { value: 1, label: '男' },
  { value: 2, label: '女' },
  ])
  
  


// 从本地存储获取用户信息
const userInfo = uni.getStorageSync('userInfo') || {};
const formData = ref({
  id: userInfo.id,
  avatar: userInfo.avatar,
  nickname: userInfo.nickname,
  gender: userInfo.gender,
  country: userInfo.country,
  province: userInfo.province,
  city: userInfo.city,
  genderValue:userInfo.genderValue
});

// 省份
const onChangeProvinc= (event)=>{
	console.log(event);
	// 当前选中的数据对象
	let item = provinceArray.value[event.detail.value];
	// 赋值给省份
	formData.value.province = item.district;
	getCity(item.id).then(res => {
		console.log("id",res)
		cityArray.value = res.data;
	})
}

// 城市
const onChangeCity = (event) => {
	console.log("evet", event)
	formData.value.city = cityArray.value[event.detail.value].district;
}

const handProvinc =()=>{
	getProvince().then((res)=>{
		console.log(res);
		provinceArray.value=res.data;
		const pid=provinceArray.value.id
		getCity(pid).then((res)=>{
			console.log(res);
		})
	})
}


const reviseAvatar = () => {
	uni.chooseImage({
		count: 1,
		sizeType: ['compressed'],
		success: async (res) => {
			const tempFile = res.tempFiles[0];

			uni.showLoading({ title: '上传中...' });

			try {
				// 上传头像逻辑
				const uploadRes = await uni.uploadFile({
					url: `${base_url}/ffile/upload`, 
					filePath: tempFile.path,
					name: 'file'
				});

				const data = JSON.parse(uploadRes.data);
				formData.value.avatar = data.data.url; 
				
				// 更新本地存储
				const userInfo = uni.getStorageSync('userInfo') || {};
				userInfo.avatar = data.url;
				uni.setStorageSync('userInfo', userInfo);
				
				uni.showToast({ title: '头像已更新' });
			} catch (err) {
				console.error('上传失败:', err);
				uni.showToast({ title: '上传失败', icon: 'none' });
			} finally {
				uni.hideLoading();
			}
		}
	});
};

const onChangeGender=(event)=>{
	console.log("event", event)
	 // 获取用户选择的索引
	  const index = event.detail.value;
	  // 更新选中的索引，触发计算属性的setter
	  console.log(genderArray);
	  formData.value.genderValue = genderArray.value[index].label;
	  formData.value.gender = genderArray.value[index].value;
}

// 将对象转换为查询字符串的函数（若后端需要 JSON 格式，可省略此函数）
function objectToQueryString(obj) {
  const params = new URLSearchParams();
  for (const [key, value] of Object.entries(obj)) {
    if (value !== null && value !== undefined) {
      params.append(key, value.toString());
    }
  }
  return params.toString();
}



const editUser = async () => {
  try {
    const requestData = objectToQueryString(formData.value);
    const res = await putUserInfo(requestData);
    
    console.log('接口响应:', res);
    
    if (res.code === 200) {
      // 1. 更新本地用户信息
      uni.setStorageSync('userInfo', { ...userInfo, ...formData.value });
      
      // 2. 提示用户操作成功
      uni.showToast({
        title: '信息已保存',
        icon: 'none', 
        duration: 1500 // 提示显示时长
      });
      
      // 3. 返回上一页
      uni.navigateBack({ delta: 1 }); // delta 为回退的页面数，默认 1
      
    } else {
      uni.showToast({
        title: res.message || '保存失败，请重试',
        icon: 'none',
        duration: 2000
      });
    }
  } catch (error) {
    console.error('网络请求失败:', error);
    uni.showToast({
      title: '网络连接失败，请检查网络',
      icon: 'none',
      duration: 2000
    });
  }
};
</script>

<style lang="scss" scoped>
	.user-info-page {
		padding: 40rpx 30rpx;
		background: #f8f9fa;
		// min-height: 100vh;
	}

	.avatar-block {
		text-align: center;
		margin-bottom: 60rpx;

		.user-avatar {
			width: 240rpx;
			height: 240rpx;
			border-radius: 50%;
			margin: 0 auto 20rpx;
			background: #f0f0f0;
		}
	}

	.info-form {
		// background: #fff;
		// padding: 40rpx;
		border-radius: 24rpx;
		box-shadow: 0 8rpx 16rpx rgba(0, 0, 0, 0.05);

		.form-item {
			display: flex;
			align-items: center;
			padding: 30rpx 0;
			border-bottom: 1rpx solid #f5f5f5;

			&:last-child {
				border-bottom: none;
			}

			.form-label {
				font-size: 34rpx;
				color: #333;
				min-width: 180rpx;
				margin-right: 30rpx;
			}

			.form-input {
				flex: 1;
				height: 80rpx;
				font-size: 32rpx;
				color: #666;
				padding-left: 20rpx;
				border: none;
				background: transparent;
				outline: none;
				opacity: 0.8;
			}
		}
	}
	
	.btn {
		background-color: #007aff;
		color: #fff;
	}
</style>